package mspbots.timedoctor.client.core.api;

import lombok.extern.slf4j.Slf4j;
import mspbots.timedoctor.client.core.BaseGenericService;
import mspbots.timedoctor.client.core.client.DoctorV1Client;
import mspbots.timedoctor.client.core.client.DoctorV2Client;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * data.connector.timedoctor.BaseApiService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/3/25
 */
@Slf4j
public abstract class BaseApiService extends BaseGenericService {


    protected DoctorV1Client doctorV1Client;
    protected DoctorV2Client doctorV2Client;

    @Autowired
    public void setDoctorV1Client(DoctorV1Client doctorV1Client) {
        this.doctorV1Client = doctorV1Client;
    }

    @Autowired
    public void setDoctorV2Client(DoctorV2Client doctorV2Client) {
        this.doctorV2Client = doctorV2Client;
    }

    public void updateSyncStatus(String key, Map value) {
        this.reactiveRedisTemplate.opsForValue()
                .set(key, value)
                .subscribe(result -> {
                    log.debug("Redis set ({}, {}) success.", key, value);
                }, err -> {
                    log.error("Redis set {} error.", key);
                });
    }

    protected void recordRedisValue(String key, String value) {
        this.stringRedisTemplate.opsForValue().set(REDIS_KEY_PREFIX + key, value).subscribe();
    }

    protected Mono<LocalDateTime> loadRedisValue(String key) {
        return this.stringRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX + key)
                .map(LocalDateTime::parse)
                .defaultIfEmpty(LocalDateTime.now().minusDays(7));
    }

}
